<template>
  <v-dialog v-model="dialogVisible" persistent max-width="85%">
    <v-card>
      <v-card-title>
        设备评估详情: {{ deviceData?.name }} ({{ deviceData?.model }})
        <v-spacer></v-spacer>
        <v-btn icon="mdi-close" variant="text" @click="closeDialog"></v-btn>
      </v-card-title>
      <v-divider></v-divider>

      <v-card-text v-if="deviceData && deviceData.evaluation && !deviceData.error" class="py-4">
        <v-row justify="space-around" class="mb-4">
          <v-col cols="12" md="auto" class="text-center">
            <div class="text-subtitle-1">设备原价值</div>
            <strong class="text-h5">{{ deviceData.initialValue ? deviceData.initialValue.toFixed(2) : '-' }} 元</strong>
          </v-col>
          <v-col cols="12" md="auto" class="text-center">
            <div class="text-subtitle-1">总得分</div>
            <strong class="text-h4">{{ deviceData.evaluation.totalScore ? deviceData.evaluation.totalScore.toFixed(4) : '-' }}</strong>
          </v-col>
          <v-col cols="12" md="auto" class="text-center">
            <div class="text-subtitle-1">评估等级</div>
            <strong class="text-h4" :style="gradeStyle">{{ deviceData.evaluation.grade }}</strong>
          </v-col>
          <v-col cols="12" md="auto" class="text-center">
            <div class="text-subtitle-1">评估价值</div>
            <strong class="text-h4">{{ deviceData.evaluation.finalRealPrice !== null ? deviceData.evaluation.finalRealPrice.toFixed(2) : '-' }} 元</strong>
          </v-col>
        </v-row>
        <div v-if="deviceData.evaluation.grade === '建议报废'" class="text-center mb-4" style="color: black;">建议报废</div>

        <v-expansion-panels>
          <v-expansion-panel
              v-for="(primaryIndicator) in Object.keys(primaryIndicatorWeights)"
              :key="primaryIndicator"
          >
            <v-expansion-panel-title style="color: #4a90e2; font-size: 20px">{{ primaryIndicator }}</v-expansion-panel-title>
            <v-expansion-panel-text>
              <v-list dense>
                <v-list-item
                    v-for="(indicator, index) in filteredSecondaryIndicators(primaryIndicator)"
                    :key="index" style="text-align: center"
                >
                  <template v-slot:title>
                    {{ indicator.name }}
                  </template>
                  <template v-slot:subtitle>
                    原始测定值: {{ getOriginalScore(indicator.name) ?? '-' }} {{ indicator.unit || '' }}
                    <span class="ml-4">评估值: {{ deviceData.evaluation.normalizedValues[indicator.name] ? deviceData.evaluation.normalizedValues[indicator.name].toFixed(4) : '-' }}</span>
                    <span class="ml-4">加权得分: {{ deviceData.evaluation.weightedScores[indicator.name] ? deviceData.evaluation.weightedScores[indicator.name].toFixed(4) : '-' }}</span>
                  </template>
                </v-list-item>
              </v-list>
            </v-expansion-panel-text>
          </v-expansion-panel>
        </v-expansion-panels>

      </v-card-text>
      <v-card-text v-else-if="deviceData && deviceData.error">
        <v-alert type="error" border="start" colored-border elevation="2">
          无法显示详情，评估过程中发生错误：{{ deviceData.error }}
        </v-alert>
      </v-card-text>
      <v-card-text v-else>
        <v-alert type="info">
          加载设备详情中...
        </v-alert>
      </v-card-text>

      <v-divider></v-divider>
      <v-card-actions>
        <v-spacer></v-spacer>
        <v-btn
            color="success"
            @click="generateReport"
            :disabled="!deviceData || !deviceData.evaluation || deviceData.error"
        >
          生成 PDF 报告
        </v-btn>
        <v-btn color="primary" variant="tonal" @click="closeDialog">关闭</v-btn>
      </v-card-actions>
    </v-card>
  </v-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue';

const props = defineProps({
  modelValue: { // Controls dialog visibility (use v-model)
    type: Boolean,
    required: true,
  },
  deviceData: { // Full data object for the selected device
    type: Object,
    default: null
  },
  // Pass necessary config data if not globally available in service
  secondaryIndicators: {
    type: Array,
    required: true,
  },
  primaryIndicatorWeights: {
    type: Object,
    required: true,
  }
});

const emit = defineEmits(['update:modelValue', 'generate-report']);

const dialogVisible = ref(props.modelValue);

// Sync dialog visibility with v-model
watch(() => props.modelValue, (newValue) => {
  dialogVisible.value = newValue;
});

function closeDialog() {
  dialogVisible.value = false;
  emit('update:modelValue', false); // Update parent's v-model
}

// --- Reuse computed properties and methods from original component ---
const gradeColors = { /* ... same colors ... */ };

const gradeStyle = computed(() => {
  const grade = props.deviceData?.evaluation?.grade;
  const color = gradeColors[grade] || 'black';
  return { color };
});

function filteredSecondaryIndicators(primaryIndicator) {
  return props.secondaryIndicators.filter(indicator => indicator.primaryIndicator === primaryIndicator);
}

function getOriginalScore(indicatorName) {
  if (!props.deviceData || !props.deviceData.bScores) return null;
  const match = indicatorName.match(/\((B\d+)\)/);
  if (match && props.deviceData.bScores[match[1]] !== undefined) {
    return props.deviceData.bScores[match[1]];
  }
  return null;
}

function generateReport() {
  if (props.deviceData) {
    emit('generate-report', props.deviceData);
  }
}

</script>

<style scoped>
/* Add styles if needed */
</style>